package test05;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 元宇宙模块 - 语音聊天模块
 */
class VoiceChatModule {
    public void processVoiceMessage(String message) {
        DigitalHumanManager manager = DigitalHumanManager.getInstance();
        System.out.println("语音模块 - 处理消息: " + message);
        manager.performAction("语音聊天: " + message);
    }
}

/**
 * 元宇宙模块 - 动作捕捉模块
 */
class MotionCaptureModule {
    public void captureMotion(String data) {
        DigitalHumanManager manager = DigitalHumanManager.getInstance();
        System.out.println("动作模块 - 捕捉动作数据: " + data);
        manager.performAction("动作捕捉: " + data);
    }
}

/**
 * 元宇宙模块 - 资产交易模块
 */
class AssetTradingModule {
    public void tradeAsset(String assetId) {
        DigitalHumanManager manager = DigitalHumanManager.getInstance();
        System.out.println("资产模块 - 交易资产: " + assetId);
        manager.performAction("资产交易: " + assetId);
    }
}

/**
 * 测试类 - 验证单例模式
 */
public class MetaversePlatform {
    public static void main(String[] args) {
        System.out.println("=== 元宇宙数字人身份管理器测试 ===\n");

        // 测试1: 基本功能测试
        System.out.println("--- 测试1: 基本功能测试 ---");
        DigitalHumanManager manager1 = DigitalHumanManager.getInstance();
        DigitalHumanManager manager2 = DigitalHumanManager.getInstance();

        System.out.println("manager1 == manager2: " + (manager1 == manager2));
        System.out.println("manager1 hashCode: " + manager1.hashCode());
        System.out.println("manager2 hashCode: " + manager2.hashCode());

        // 初始化数字人
        manager1.initializeAvatar("user_123456");

        // 测试功能
        manager1.performAction("挥手");
        manager1.performAction("跳舞");

        System.out.println("\n" + manager1.getAvatarInfo());

        // 测试2: 多线程环境测试
        System.out.println("--- 测试2: 多线程环境测试 ---");
        testConcurrentAccess();

        // 测试3: 多模块使用测试
        System.out.println("--- 测试3: 多模块使用测试 ---");
        testMultipleModules();

        // 测试4: 防止反射攻击测试
        System.out.println("--- 测试4: 防止反射攻击测试 ---");
        testReflectionAttack();
    }

    /**
     * 测试多线程并发访问
     */
    private static void testConcurrentAccess() {
        final int threadCount = 5;
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch endLatch = new CountDownLatch(threadCount);
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        System.out.println("创建 " + threadCount + " 个线程并发获取单例实例...");

        for (int i = 0; i < threadCount; i++) {
            final int threadId = i;
            executor.execute(() -> {
                try {
                    startLatch.await(); // 等待同时开始

                    DigitalHumanManager manager = DigitalHumanManager.getInstance();
                    System.out.println("线程 " + threadId + " 获取实例 - HashCode: " + manager.hashCode());

                    if (!manager.isInitialized()) {
                        manager.initializeAvatar("concurrent_user_" + threadId);
                    }

                    manager.performAction("线程" + threadId + "动作");

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    endLatch.countDown();
                }
            });
        }

        // 同时启动所有线程
        startLatch.countDown();

        try {
            endLatch.await(); // 等待所有线程完成
            executor.shutdown();
            System.out.println("✅ 多线程测试完成 - 所有线程使用同一个实例");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 测试多模块使用
     */
    private static void testMultipleModules() {
        VoiceChatModule voiceModule = new VoiceChatModule();
        MotionCaptureModule motionModule = new MotionCaptureModule();
        AssetTradingModule assetModule = new AssetTradingModule();

        voiceModule.processVoiceMessage("你好，元宇宙！");
        motionModule.captureMotion("跳舞动作数据");
        assetModule.tradeAsset("NFT_001");

        // 验证所有模块使用同一个数字人实例
        DigitalHumanManager manager = DigitalHumanManager.getInstance();
        System.out.println("\n所有模块共享同一个数字人实例:");
        System.out.println(manager.getAvatarInfo());
    }

    /**
     * 测试防止反射攻击
     */
    private static void testReflectionAttack() {
        try {
            System.out.println("尝试通过反射创建新实例...");

            // 获取私有构造器
            java.lang.reflect.Constructor<DigitalHumanManager> constructor =
                    DigitalHumanManager.class.getDeclaredConstructor();
            constructor.setAccessible(true); // 设置可访问

            // 尝试创建新实例 - 应该抛出异常
            DigitalHumanManager reflectedInstance = constructor.newInstance();

            System.out.println("❌ 反射攻击成功 - 这不应该发生！");

        } catch (Exception e) {
            System.out.println("✅ 反射攻击被阻止: " + e.getMessage());
        }
    }
}
